import React, { useState, useEffect } from 'react'
import { useHistory } from 'react-router-dom'
import moment from 'moment'
import { Table, Button } from 'antd'
import { getUserList, delUserById } from '@/api/user'
import { typeUserInfo } from '@/types/user'
import { showLoading, hideLoading, $confirm } from '@/register/globalFun'
import './index.scss'
import { loadingFn } from '../../../utils/tools'

const pageSize = 10
const UserList = () => {
  const history = useHistory()
  const [userList, setUserList]:[typeUserInfo[], any] = useState([])
  const [current, setCurrent] = useState(1)
  const [total, setTotal] = useState(0)

  useEffect(() => {
    loadUserList(1)
  }, [])

  /**
   * 加载用户列表
   */
  const loadUserList = async(pageNum = current) => {
    loadingFn(async() => {
      const res = await getUserList({
        pageNum,
        pageSize
      })

      setUserList(res.data.users)
      setTotal(res.data.total)
      setCurrent(pageNum)
      console.log(res.data)
    })
  }

  /**
   * 点击删除用户
   */
  const onclickDelUser = async(index:number, userId:string) => {
    $confirm('确认删除该用户?', async() => {
      await delUserById(userId)
      const tempList = [...userList]

      tempList.splice(index, 1)
      setUserList(tempList)
    })
  }

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: '注册时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text:string, record:typeUserInfo) => (
        <span key={record._id}>{moment(text).format('YYYY/MM/DD HH:mm:ss')}</span>
      )
    },
    {
      title: '操作',
      key: 'control',
      render: (text:string, record:typeUserInfo, index:number) => (
        <div>
          <Button
            onClick={() => {
              history.push(`/admin/user-edit/${ record._id }`)
            }}
            size="small"
            style={{ marginRight: '10px' }}
          >
            查看详情
          </Button>
          <Button
            danger
            onClick={() => onclickDelUser(index, record._id)}
            size="small"
          >
              删除用户
          </Button>
        </div>

      )
    },
  ]

  return (
    <div className="user-list">
      <Table
        columns={columns}
        dataSource={userList}
        pagination={{
          position: ['bottomRight'],
          pageSize,
          current,
          total,
          onChange: (current:number) => {
            loadUserList(current)
          }
        }}
        rowKey={(record:typeUserInfo) => record._id || ''}
      />
    </div>
  )
}

export default UserList
